using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Serialization;

namespace KickStart.Helpers
{
    public class JsonPoxAttribute : ActionFilterAttribute
    {
        private static readonly UTF8Encoding UTF8 = new UTF8Encoding(false);

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var view = (ViewResult)(filterContext.Result);
            filterContext.Result = GetResult(filterContext.HttpContext, view.ViewData.Model);

        }

        public static ActionResult GetResult(HttpContextBase httpContext, object data)
        {
            // setup the request, view and data 
            var request = httpContext.Request;
            var contentType = request.AcceptTypes.Count() > 1
                                  ?
                                      request.AcceptTypes[0] ?? string.Empty
                                  : string.Empty;
            var format = string.IsNullOrEmpty(request.QueryString["format"])
                             ? string.Empty
                             : request.QueryString["format"].ToLower();

            // JSON 
            if (format == "json" || contentType.Contains("application/json"))
            {
                return new JsonResult
                                           {
                                               Data = data
                                           };
            }
            // POX 
            else if (format == "xml" || contentType.Contains("text/xml") || contentType.Contains("application/xml"))
            {
                // MemoryStream to encapsulate as UTF-8 (default UTF-16) 
                // http://stackoverflow.com/questions/427725/ 
                using (var stream = new MemoryStream(500))
                {
                    using (var xmlWriter =
                        XmlWriter.Create(stream,
                                         new XmlWriterSettings()
                                             {
                                                 // Plain Old XML (no XML headers) 
                                                 OmitXmlDeclaration = true,
                                                 Encoding = UTF8,
                                                 Indent = true
                                             }))
                    {
                        new XmlSerializer(data.GetType()).Serialize(xmlWriter, data);
                    }
                    return new ContentResult
                                               {
                                                   ContentType = "text/xml",
                                                   Content = UTF8.GetString(stream.ToArray()),
                                                   ContentEncoding = UTF8
                                               };
                }
            }
            return null;
        }
    }
}